package shared

import (
	"database/sql"
	"strings"
)

type SqlHelper struct {}

// Manages the db connection and calls the input function with opened connection.
// If the driverName or dataSourceName is not provided the default value will be applied.
func (SqlHelper) WithDbConnection(fn func(db *sql.DB), driverName string, dataSourceName string) error  {
	// Checks on driverName and applies default value if needed.
	if strings.TrimSpace(driverName) == "" {
		driverName = "mysql"
	}

	// Checks on dataSourceName and applies default value if needed.
	if strings.TrimSpace(dataSourceName) == "" {
		// Can set with app config
		dataSourceName = ""
	}

	// Opens db connection with related info.
	db, err := sql.Open(driverName, dataSourceName)

	// If error occurs during open then the error will be returned and the input function is not called.
	if err != nil {
		return err
	}

	// Makes sure the connection will be closed.
	defer db.Close()

	// Calls input function with opened connection.
	fn(db)

	return nil
}